<template>
  <div class="container" style="height: 100%">
    <div class="flex_cm" style="height: 100%">
      <search
        :data="header_list"
        @changeIsShow="
          (e) => {
            header_list[e].isShow = !header_list[e].isShow
            header_list[e].value =
              header_list[e].type == 'input_number' ? ['', ''] : ''
          }
        "
        @search="search_key"
        @reset="
          header_list.forEach((item) => {
            item.value = ''
          }),
            search_key()
        "
      ></search>
      <div class="p_0_10 bg_fff flex1">
        <div class="flex_js p_10_0">
          <div class="c_666 fw">深化插件价格设置</div>
          <div class="flex">
            <el-button
              type="primary"
              @click="show_add_box = true"
              v-if="role_list[3].has_role"
              >新增</el-button
            >

            <setTable
              :data="header_list"
              :height_size="height_size"
              @changeShowTable="
                (e) => {
                  header_list[e].showTable = !header_list[e].showTable
                }
              "
              @resetTableSet="
                () => {
                  header_list.forEach((item) => {
                    item.showTable = true
                  })
                }
              "
              @changeHeightSize="
                (e) => {
                  height_size = e
                }
              "
            ></setTable>
          </div>
        </div>
        <el-table
          style="text-align: center"
          :data="list"
          :max-height="max_height"
          border
          v-loading="loading"
          :default-sort="{ prop: 'name', order: 'descending' }"
          :row-style="{
            height: height_size == 2 ? '50px' : '',
          }"
          :cell-style="{
            padding: height_size == 3 ? '0' : '',
          }"
        >
          <el-table-column
            type="index"
            label="序号"
            width="80px"
          ></el-table-column>
          <el-table-column
            label="申请单号"
            prop="code"
            key="申请单号"
            sortable
            v-if="header_list[0].showTable"
          ></el-table-column>
          <el-table-column
            label="申请日期"
            key="申请日期"
            sortable
            prop="applyTime"
            v-if="header_list[1].showTable"
          >
            <template #default="scope: any">
              <div>
                {{ formatDate(parseInt(scope.row.applyTime), 'yyyy-MM-dd') }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="申请人"
            prop="applyManagerUserName"
            key="申请人"
            sortable
            v-if="header_list[2].showTable"
          >
          </el-table-column>
          <el-table-column
            label="新价格启用日期"
            key="新价格启用日期"
            sortable
            prop="enableTime"
            v-if="header_list[3].showTable"
            ><template #default="scope: any">
              <div>
                {{ formatDate(parseInt(scope.row.enableTime), 'yyyy-MM-dd') }}
              </div>
            </template></el-table-column
          >
          <el-table-column
            label="备注"
            key="备注"
            sortable
            prop="remark"
            v-if="header_list[4].showTable"
          >
            <template #default="scope: any">
              <div class="text_over" style="width: 100%">
                <el-tooltip :content="scope.row.remark" placement="bottom">
                  {{ scope.row.remark }}
                </el-tooltip>
              </div>
            </template></el-table-column
          >
          <el-table-column label="操作" width="124px">
            <template #default="scope: any">
              <table_edit
                v-if="scope.row.status == 1"
                :role="role_list"
                @edit_item_status="exam_list(scope)"
                @edit_item="update_list(scope)"
                @delete_item="delete_list(scope)"
              ></table_edit>
              <el-tooltip
                v-if="scope.row.status == 2 && role_list[4].has_role"
                content="详情"
                placement="bottom"
              >
                <SvgButton
                  icon="table_info"
                  style="font-size: 20px"
                  @click="exam_list(scope)"
                ></SvgButton>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <el-drawer
      v-model="show_add_box"
      destory-on-close
      direction="rtl"
      @close="resetForm(addDeepPulginPriceForm)"
      size="80%"
      :close-on-click-modal="false"
    >
      <template #title>
        <h4 v-if="is_exam">审核深化插件价格</h4>
        <div v-else>
          <h4 v-if="add_form_data.id == ''">新增深化插件价格</h4>
          <h4 v-else>编辑深化插件价格</h4>
        </div>
      </template>
      <template #default>
        <el-form
          :model="add_form_data"
          :rules="rules"
          ref="addDeepPulginPriceForm"
          label-width="150px"
        >
          <div class="foem_box">
            <el-form-item label="申请日期" prop="applyTime">
              <el-date-picker
                placeholder="请选择"
                type="date"
                format="YYYY-MM-DD"
                value-format="x"
                v-model="add_form_data.applyTime"
                :disabled="is_exam"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="申请人">
              <el-input disabled v-model="add_form_data.applyName"></el-input>
            </el-form-item>
            <el-form-item label="新价格启用日期" prop="enableTime">
              <el-date-picker
                placeholder="请选择"
                type="date"
                :disabled-date="disabledEnabledTime"
                format="YYYY-MM-DD"
                value-format="x"
                v-model="add_form_data.enableTime"
                :disabled="is_exam"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="备注">
              <el-input
                v-model="add_form_data.remark"
                placeholder="请输入"
                :disabled="is_exam"
                show-word-limit
                maxlength="300"
              ></el-input>
            </el-form-item>
          </div>
          <h4 class="m_top20">插件价格设置</h4>
          <el-table :data="deepPluginList" border class="tc price_table">
            <el-table-column
              type="index"
              label="序号"
              width="80px"
              fixed
            ></el-table-column>
            <el-table-column label="起始量" width="100px" fixed>
              <template #default="scope: any">
                <el-input
                  type="number"
                  placeholder="请输入"
                  v-model="scope.row.beginNum"
                  :disabled="
                    is_exam || (scope.row.beginNum == 1 && scope.$index == 0)
                  "
                  @input="
                    scope.row.beginNum = scope.row.beginNum.replace(
                      /^(0+)|[^\d]+/g,
                      ''
                    )
                  "
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="终止量" width="100px" fixed>
              <template #default="scope: any">
                <el-input
                  type="number"
                  placeholder="请输入"
                  @input="
                    scope.row.endNum = scope.row.endNum.replace(
                      /^(0+)|[^\d]+/g,
                      ''
                    )
                  "
                  v-model="scope.row.endNum"
                  :disabled="is_exam"
                ></el-input> </template
            ></el-table-column>
            <el-table-column>
              <template #header>
                <span>每用户/(n)月价格</span>
                <el-popover trigger="click" placement="top" :width="160">
                  <p>请输入月数</p>
                  <el-input
                    class="m_10_0 month_input"
                    type="number"
                    @input="
                      add_month_num = add_month_num.replace(/^(0+)|[^\d]+/g, '')
                    "
                    v-model="add_month_num"
                    placeholder="请输入正整数"
                  ></el-input>
                  <div style="text-align: right; margin: 0">
                    <el-button
                      size="small"
                      type="primary"
                      @click="submit_add_month_num"
                      >确定</el-button
                    >
                  </div>
                  <template #reference>
                    <el-button
                      v-show="deepPluginList.length && !is_exam"
                      type="primary"
                      size="small"
                      class="m_left10"
                      >追加列</el-button
                    >
                  </template>
                </el-popover>
                <el-popover trigger="click" placement="right" :width="360">
                  <el-table :data="month_list" max-height="300px">
                    <el-table-column width="150" prop="monthNum" label="月数" />
                    <el-table-column label="操作">
                      <template #default="scope: any">
                        <el-button @click="delete_month_list(scope.$index)"
                          >删除</el-button
                        >
                      </template>
                    </el-table-column>
                  </el-table>
                  <template #reference>
                    <el-button
                      v-show="month_list.length && !is_exam"
                      class="m_left10"
                      >删除列</el-button
                    >
                  </template>
                </el-popover>
              </template>
              <el-table-column
                v-for="(item, index) in month_list"
                :label="item.monthNum + ' 个月'"
                min-width="100px"
              >
                <template #default="scope: any">
                  <el-input
                    type="number"
                    v-model="scope.row.plugPriceItemDetails[index].price"
                    placeholder="请输入"
                    :disabled="is_exam"
                  ></el-input>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column label="备注" width="200px">
              <template #default="scope: any">
                <el-input
                  v-model="scope.row.remark"
                  placeholder="请输入"
                  :disabled="is_exam"
                ></el-input>
              </template>
            </el-table-column>
          </el-table>
          <div>
            <el-button
              type="primary"
              v-if="!is_exam"
              class="m_top10"
              @click="add_deepPluginList"
              >追加一行</el-button
            >
            <el-button
              type="primary"
              v-if="!is_exam && deepPluginList.length > 1"
              class="m_top10"
              @click="deepPluginList.splice(deepPluginList.length - 1, 1)"
              >删除最后一行</el-button
            >
          </div>
          <el-divider style="margin-top: 10px"></el-divider>
          <div class="m_top10 tr">
            <el-button @click="resetForm(addDeepPulginPriceForm)"
              >取消</el-button
            >
            <el-button
              v-if="!is_exam"
              type="primary"
              :loading="btn_loading"
              @click="submit(addDeepPulginPriceForm)"
              >确定</el-button
            >
            <el-button
              v-if="is_exam && add_form_data.status == '1'"
              type="primary"
              :loading="btn_loading"
              @click="exam"
              >审核</el-button
            >
          </div>
        </el-form>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { check_role, formatDate, handle_search_key } from '@/utils/utils' // 权限校验
import search from '@/view/components/search.vue'
import setTable from '@/view/components/setTable.vue'
import table_edit from '@/view/components/table_edit.vue'
import { onMounted, ref, onUnmounted, reactive } from 'vue'
import SvgButton from '@/components/svg_button.vue'
import axios from '@/service/HttpRequest'
import serviceApi from '@/service/api'
import EventBus from '@/utils/EventBus'
import { useStore } from 'vuex'
import { ElMessage, FormRules, FormInstance, ElMessageBox } from 'element-plus'
const addDeepPulginPriceForm = ref<FormInstance>()
const rules = reactive<FormRules>({
  enableTime: [
    {
      required: true,
      type: 'date',
      message: '请选择启用日期',
      trigger: 'change',
    },
  ],
  applyTime: [
    {
      required: true,
      type: 'date',
      message: '请选择申请日期',
      trigger: 'change',
    },
  ],
})
const role_list = ref([
  { path: 'deepPluginPrice/pass', has_role: false },
  { path: 'deepPluginPrice/put', has_role: false },
  { path: 'deepPluginPrice/delete', has_role: false },
  { path: 'deepPluginPrice/post', has_role: false },
  { path: 'deepPluginPrice/info', has_role: false },
])
const disabledEnabledTime = (time: Date) => {
  return add_form_data.value.applyTime != ''
    ? time.getTime() <
        parseInt(add_form_data.value.applyTime) + 3600 * 1000 * 24
    : time.getTime() < Date.now() - 3600 * 1000 * 24 * 1
}
const store = useStore()
const list = ref()
const max_height = ref()
const loading = ref(false)
const show_add_box = ref(false)
const height_size = ref(1)
const header_list = ref<any>([
  {
    label: '申请单号',
    value: '',
    showTable: true,
    type: 'input',
    isShow: true,
    options: [],
  },
  {
    label: '申请日期',
    value: '',
    showTable: true,
    type: 'date',
    isShow: true,
    options: [],
  },
  {
    label: '申请人',
    value: '',
    showTable: true,
    type: 'input',
    isShow: true,
    options: [],
  },
  {
    label: '新价格启用日期',
    value: '',
    showTable: true,
    type: 'date',
    isShow: false,
    options: [],
  },
  {
    label: '备注',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
  },
])
const page_data = ref({
  current: 1,
  pageSize: 1000,
  applicant: '',
  applyTime: '',
  enableTime: '',
  code: '',
  remark: '',
})
const add_form_data = ref({
  id: '',
  applyTime: '',
  enableTime: '',
  plugPriceItems: [],
  applyName: store.state.user_info.username,
  remark: '',
  status: '1',
})
const delete_month_list = (e) => {
  console.log(e)
  month_list.value.splice(e, 1)
  // 删除列 - 每一行都删除
  deepPluginList.value.forEach((item) => {
    item.plugPriceItemDetails.splice(e, 1)
  })
}
const add_month_num = ref()
const submit_add_month_num = () => {
  console.log(add_month_num.value)
  if (add_month_num.value == '') {
    ElMessage.error('请输入月数')
    return
  }
  let is_has_month = month_list.value.some((item) => {
    return item.monthNum == add_month_num.value
  })
  if (is_has_month) {
    ElMessage.error('已经存在该数量的月数')
    return
  }
  let month_obj = {
    monthNum: add_month_num.value,
  }
  month_list.value.push(month_obj)
  month_list.value.sort((a, b) => {
    return a.monthNum - b.monthNum
  })
  // 追加列 - 每一行都追加
  deepPluginList.value.forEach((item) => {
    let obj_item = {
      monthNum: add_month_num.value,
      price: '',
    }
    item.plugPriceItemDetails.push(obj_item)
    item.plugPriceItemDetails.sort((a, b) => {
      return a.monthNum - b.monthNum
    })
  })

  add_month_num.value = ''
}
const deepPluginList = ref([])
const add_deepPluginList = () => {
  let flag = deepPluginList.value.some((item) => {
    return item.beginNum == '' || item.endNum == ''
  })
  if (flag) {
    ElMessage.error('请优先完成上一行的起始数、终止数')
    return
  }
  // 追加行 - 每一列都追加
  let price_list = []
  month_list.value.forEach((item) => {
    let obj_item = {
      monthNum: item.monthNum,
      price: '',
    }
    price_list.push(obj_item)
  })
  let item = {
    beginNum: deepPluginList.value.length == 0 ? '1' : '',
    endNum: '',
    plugPriceItemDetails: price_list,
    remark: '',
  }
  deepPluginList.value.push(item)
}
const month_list = ref([])
onMounted(() => {
  role_list.value.forEach((item) => {
    item.has_role = check_role(item.path)
  })
  max_height.value = window.innerHeight - 320 // 不带分页的 table 高度
  EventBus.on('refresh', () => {
    get_list()
    ElMessage.success('操作成功！')
  })
  get_list()
})
onUnmounted(() => {
  EventBus.off('refresh')
})
const delete_list = (e) => {
  ElMessageBox.confirm(
    '确定删除申请单号为：' + e.row.code + ' 的记录',
    '提示',
    {
      cancelButtonText: '取消',
      confirmButtonText: '确定',
      closeOnClickModal: false,
      type: 'warning',
    }
  )
    .then(() => {
      axios
        .request({
          url: serviceApi.deepPluginPrice_curd + '/' + e.row.id,
          method: 'delete',
        })
        .then(() => {
          ElMessage.success('操作成功！')
          setTimeout(() => {
            get_list()
          }, 1000)
        })
        .catch((err) => {
          ElMessage.error(err)
        })
    })
    .catch(() => {})
}
const is_exam = ref(false) // 操作是否为审核
const exam_list = (e) => {
  is_exam.value = true
  get_current_item(e)
}
const exam = (e) => {
  ElMessageBox.confirm('确定审核该条记录', '提示', {
    cancelButtonText: '取消',
    confirmButtonText: '确定',
    closeOnClickModal: false,
    type: 'warning',
  })
    .then(() => {
      axios
        .request({
          url: serviceApi.deepPluginPrice_pass + '/' + add_form_data.value.id,
          method: 'put',
          data: {
            status: 2,
          },
        })
        .then(() => {
          ElMessage.success('操作成功！')
          setTimeout(() => {
            show_add_box.value = false
            get_list()
          }, 1000)
        })
        .catch((err) => {
          ElMessage.error(err)
        })
    })
    .catch(() => {})
}
const update_list = (e) => {
  get_current_item(e)
}
const get_current_item = (e) => {
  axios
    .request({
      url: serviceApi.deepPluginPrice_curd + '/' + e.row.id,
      method: 'get',
    })
    .then((res) => {
      console.log(res)
      store.state.user_list.some((item) => {
        if (item.id == res.data.applicant) {
          add_form_data.value.applyName = item.username
        }
      })
      add_form_data.value = {
        id: res.data.id,
        applyTime: parseInt(res.data.applyTime) as any,
        enableTime: parseInt(res.data.enableTime) as any,
        plugPriceItems: [],
        applyName: add_form_data.value.applyName,
        remark: res.data.remark,
        status: res.data.status + '',
      }
      deepPluginList.value = res.data.plugPriceItems
      if (
        res.data.plugPriceItems.length &&
        res.data.plugPriceItems[0].plugPriceItemDetails.length
      ) {
        res.data.plugPriceItems[0].plugPriceItemDetails.forEach((item) => {
          month_list.value.push({ monthNum: item.monthNum })
        })
      }
      console.log(month_list.value)
      show_add_box.value = true
    })
}
const btn_loading = ref(false)
const submit = async (formEl: FormInstance | undefined) => {
  console.log(deepPluginList.value)
  await formEl.validate((valid) => {
    if (valid) {
      if (!deepPluginList.value.length) {
        ElMessage.error('请至少设置一行插件价格')
        return
      }
      if (!month_list.value.length) {
        ElMessage.error('请至少设置一列插件价格')
        return
      }
      let is_complete = 1 // 判断价格参数 是否合理
      let has_no_price = false
      deepPluginList.value.forEach((item, index) => {
        if (item.beginNum == '' || item.endNum == '') {
          is_complete = 2
        }
        if (parseInt(item.endNum) <= parseInt(item.beginNum)) {
          is_complete = 3
        }
        if (
          index > 0 &&
          parseInt(item.beginNum) <=
            parseInt(deepPluginList.value[index - 1].endNum)
        ) {
          is_complete = 4
        }
        item.plugPriceItemDetails.forEach((item1) => {
          if (item1.price == '') has_no_price = true
        })
      })
      if (is_complete == 2) {
        ElMessage.error('请完善插件价格的起始以及结束点数')
        return
      }
      if (is_complete == 3) {
        ElMessage.error('插件价格的终止量必须大于起始量')
        return
      }
      if (is_complete == 4) {
        ElMessage.error('插件价格的起始量必须大于上一条记录的终止量')
        return
      }
      if (has_no_price) {
        ElMessage.error('请完善所有价格设置')
        return
      }

      if (btn_loading.value) return
      btn_loading.value = true
      add_form_data.value.plugPriceItems = deepPluginList.value
      axios
        .request({
          url:
            add_form_data.value.id == ''
              ? serviceApi.deepPluginPrice_curd
              : serviceApi.deepPluginPrice_curd + '/' + add_form_data.value.id,
          method: add_form_data.value.id == '' ? 'post' : 'put',
          data: add_form_data.value,
        })
        .then((res) => {
          console.log(res)
          ElMessage.success('操作成功！等待管理员审核')
          setTimeout(() => {
            btn_loading.value = false
            resetForm(formEl)
            get_list()
          }, 1000)
        })
        .catch((err) => {
          btn_loading.value = false
          ElMessage.error(err)
        })
    }
  })
}
const get_list = () => {
  loading.value = true
  axios
    .request({
      url: serviceApi.deepPluginPrice_list,
      method: 'post',
      data: handle_search_key(page_data.value),
    })
    .then((res) => {
      console.log(res)
      loading.value = false
      list.value = res.data.content
    })
    .catch((err) => {
      ElMessage.error(err)
    })
}
const search_key = () => {
  console.log(header_list.value)
  page_data.value = {
    current: 1,
    pageSize: 1000,
    code: header_list.value[0].value,
    applyTime: header_list.value[1].value,
    applicant: header_list.value[2].value,
    enableTime: header_list.value[3].value,
    remark: header_list.value[4].value,
  }
  get_list()
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  add_form_data.value = {
    id: '',
    applyTime: '',
    enableTime: '',
    plugPriceItems: [],
    applyName: store.state.user_info.username,
    remark: '',
    status: '1',
  }
  deepPluginList.value = []
  month_list.value = []
  is_exam.value = false
  show_add_box.value = false
  formEl.resetFields()
}
</script>

<style lang="scss" scoped>
.price_table {
  margin-top: 10px;
  :deep(.el-input__inner) {
    padding-right: 11px;
  }
}
.month_input {
  :deep(.el-input__inner) {
    padding-right: 11px;
  }
}
.foem_box {
  display: flex;
  flex-wrap: wrap;
  > div {
    width: 50%;
  }
}
</style>
